var mysql = require('mysql');

var databaseConfig = require('../db/config.json').database;

var chai = require('chai');
var assert = chai.assert;
var expect = chai.expect;
var should = chai.should();
var sinon = require('sinon');
var Q = require('q');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);

var config = {
  connectionLimit: databaseConfig.connectionLimit,
  host: databaseConfig.host,
  user: databaseConfig.user,
  password: databaseConfig.password,
  port: databaseConfig.port,
  database: databaseConfig.database
};

describe('数据库操作', function() {

  describe('成功虚拟数据库', function() {

    var stub;
    var spy;
    var myPool = {
      getConnection: function(cb) {
        var connection = {
          release: function() {},
          query: function(query, params, qcb) {
            var mockQueries = {
              q1: 'select * from users where schoolld =?',
			  q2: 'delete from users where schoolld = ?',
			  q3: 'update users set schoolld = 5120152560 where schoolld = ?',
			  q4: 'insert into users(schoolld) values(?)'
            }

            if (query === mockQueries.q1 && params === '5120152534') {
              return qcb(null, 'success query');
            } else {
              return qcb(new Error('fail to query'));
            }
			if (query === mockQueries.q2 && params === '5120152534') {
              return qcb(null, 'success query');
            } else {
              return qcb(new Error('fail to query'));
            }
			if (query === mockQueries.q3 && params === '5120152534') {
              return qcb(null, 'success query');
            } else {
              return qcb(new Error('fail to query'));
            }
			if (query === mockQueries.q4 && params === '5120152499') {
              return qcb(null, 'success query');
            } else {
              return qcb(new Error('fail to query'));
            }
          }
        };
        spy = sinon.spy(connection, "release");
        cb(null, connection);
      }
    };


    beforeEach(function() {
		//console.log();
	  console.log('--利用sinon模拟数据库mysql-得到成功链接');
      stub = sinon.stub(mysql, "createPool");
      stub.withArgs(config).returns(myPool);

    });

    it('--执行sql 查询学号为5120152534的用户，正确ID', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('select * from users where schoolld =?', '5120152534').should.eventually.deep.equal('success query');
      assert(spy.calledOnce);
    });

    it('--执行sql 查询学号为5120152534的用户，错误ID', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('select * from users where schoolld =?', 'WrongID').should.be.rejectedWith('fail to query');
      assert(spy.calledOnce);
    });
	
	it('--执行sql 删除学号为5120152534的用户，正确ID', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('delete from users where schoolld = ?', '5120152534').should.eventually.deep.equal('success query');
      assert(spy.calledOnce);
    });

    it('--执行sql 删除学号为5120152534的用户，错误ID', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('delete from users where schoolld = ?', 'WrongID').should.be.rejectedWith('fail to query');
      assert(spy.calledOnce);
    });
	
	it('--执行sql 修改学号为5120152560的用户的学号为5120152534，正确ID', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('update users set schoolld = 5120152560 where schoolld = ?', '5120152534').should.eventually.deep.equal('success query');
      assert(spy.calledOnce);
    });

    it('--执行sql 修改学号为5120152560的用户的学号为5120152534，错误ID', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('update users set schoolld = 5120152560 where schoolld = ?', 'WrongID').should.be.rejectedWith('fail to query');
      assert(spy.calledOnce);
    });
	
	it('--执行sql 添加学号为5120152499的用户，正确ID', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('insert into users(schoolld) values(?)', '5120151499').should.eventually.deep.equal('success query');
      assert(spy.calledOnce);
    });

    it('--执行sql 添加学号为5120152499的用户，错误ID', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('insert into users(schoolld) values(?)', 'WrongID').should.be.rejectedWith('fail to query');
      assert(spy.calledOnce);
    });
	
    afterEach('--恢复数据库mysql',function() {
		//console.log();
	  console.log('--恢复数据库mysql');
      stub.restore();
      spy.restore();
    });

  });

  describe('失败虚拟数据库', function() {

    var stub;
    var spy;

    var myPool = {
      getConnection: function(cb) {
        var connection = {
          release: function() {},
        };
        spy = sinon.spy(connection, "release");
        cb(new Error('Pool get connection error'));
      }
    };

    beforeEach('--利用sinon模拟数据库mysql-得到错误连接',function() {
		//console.log();
	  console.log('--利用sinon模拟数据库mysql-得到错误连接');
      stub = sinon.stub(mysql, "createPool");
      stub.withArgs(config).returns(myPool);
    });

    it('--执行sql数据错误，没有成功连接数据库', function() {
      delete require.cache[require.resolve('../db/jdbc.js')];
      var jdbc = require('../db/jdbc.js');
      jdbc.query('select * from t_widget where schoolld =?', '5120152534').should.be.rejectedWith('Pool get connection error');

      assert.isFalse(spy.called);
    });

    afterEach('恢复数据库mysql',function() {
		//console.log();
	  console.log('恢复数据库mysql');
      stub.restore();
      spy.restore();
    });

  });

});